//
//  StatViewController.m
//  SleepDetective
//
//  Created by Fei Hu on 12/12/10.
//  Copyright 2010 Southern Methodist University. All rights reserved.
//

#import "StatViewController.h"
#import	"SleepDetectiveAppDelegate.h"
#include <sqlite3.h>

@implementation StatViewController
@synthesize graphView;
@synthesize twitterBtn;
//@synthesize moveCountArray;



/* * * * * * * * * * * * * * * * * * * * *
 *
 *      START PROGRAMMING: FEI HU
 *
 * * * * * * * * * * * * * * * * * * * * */

// Contents loaded from db: each cell is an NSDictionary of key-val pairs
//NSMutableArray *movedataArr;	// body movement array[NSDictionary]
NSDateFormatter *dateFormatter;
NSMutableArray *moveCountArray; // count array
NSString *startSleepTime;	// start time
NSString *endSleepTime;		// end time
int currentCycle;			// current selected cycle

// Load data from DB
- (NSArray *) loadDataFromDb {
	NSLog (@"--- INFO- START -> loadDataFromDb ---");
	
	sqlite3 *db;
	int dbrc; // database return code
	SleepDetectiveAppDelegate *appDelegate = (SleepDetectiveAppDelegate*) [UIApplication sharedApplication].delegate;
	const char* dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String];
	dbrc = sqlite3_open (dbFilePathUTF8, &db);
	if (dbrc) {
		NSLog (@"--- ERROR- DB OPEN -> couldn't open db! ---");
		return;
	}
	NSLog (@"--- INFO- DB OPEN -> opened db ---");


	//
	// Select timestamps by cycle
	//
	sqlite3_stmt *dbps; // database prepared statement
	
	// EXAMPLE SQL: SELECT CYCLE,TIMESTAMP,FLAG FROM move WHERE CYCLE = (SELECT MAX(CYCLE)-MIN(CYCLE) FROM move)
	// USE SQL: SELECT CYCLE,TIMESTAMP,FLAG FROM move WHERE CYCLE = (SELECT MAX(CYCLE) FROM move)
	// to select the latest night sleep data
	NSString *queryStatementNS = @"SELECT CYCLE,TIMESTAMP,FLAG FROM move WHERE CYCLE=3;"; // only for presentation, please replace w/ max(cycle)
	
	const char *queryStatement = [queryStatementNS UTF8String];
	dbrc = sqlite3_prepare_v2 (db, queryStatement, -1, &dbps, NULL);
	NSLog (@"--- INFO - PREPARE STATEMENT -> prepared statement ---");
	
//	[movedataArr release]; //clear out any existing table model array and prepare new one
//	movedataArr = [[NSMutableArray alloc] initWithCapacity: 100]; // arbitrary capacity
	
	NSDate *sinceTime = [NSDate dateWithTimeIntervalSinceReferenceDate:0]; // Since this timestamp:2001/01/01 by default DONT AUTORELEASE!
	int count = 0; // counter
	NSMutableArray *countArr = [[[NSMutableArray alloc] init]autorelease]; // count array
	
	while ((dbrc = sqlite3_step (dbps)) == SQLITE_ROW) {
		
		currentCycle = sqlite3_column_int(dbps, 0);
//		int cycleValueI = sqlite3_column_int(dbps, 0);
//		NSNumber *cycleValue = [[NSNumber alloc] initWithInt: cycleValueI]; // cycle value
		
		NSString *timeStampValueS = [[NSString alloc] initWithUTF8String: (char*) sqlite3_column_text (dbps, 1)];
		NSDate *timeStampValue = [dateFormatter dateFromString: timeStampValueS]; // timestamp value

		endSleepTime = timeStampValueS; // set end sleep time
		
//		NSString *flagValue = [[NSString alloc] init]; // initialize flag value
//		char *flagValueS = (char *)sqlite3_column_text (dbps, 2);
//		
//		if (flagValueS != NULL) {
//			flagValue = [NSString stringWithUTF8String:flagValueS]; // flag value
//		} else {
//			flagValue = @"R"; // flag value is R
//		}
		
		/*
		 * count movements every TIME_INTERVAL mins
		 */
		
		NSDate *defaultDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
		
		if ([sinceTime isEqualToDate:defaultDate]) { // 1st loop
			NSLog(@"--- INFO -WARNING -> SINCE  TIME IS NULL! WILL BE SET W/ THE TIMESTAMP");
			sinceTime = timeStampValue;
			// set start to sleep time
			startSleepTime = timeStampValueS;
		}		
		double interval = [timeStampValue timeIntervalSinceDate:sinceTime];

		// if time interval still greater than 900 compared to the new sinceTime
		while (interval > TIME_INTERVAL) {
			// add count = 0 to  array
			[countArr addObject:[NSNumber numberWithInt:(count>8?8:count)]];
			count = 0;
			sinceTime = [sinceTime dateByAddingTimeInterval:TIME_INTERVAL];
			interval = [timeStampValue timeIntervalSinceDate:sinceTime];
		}
		count++;		
		// end of count movements
		// release our interest in all the value items
		// The string you get back from "stringWithUTF8String" is already autoreleased?
		//		[timeStampValueS release];
		//		[cycleValue release];
		//		[timeStampValue release];
		//		[flagValue release];
//		[rowDict release];
	}
	//END
	
	[countArr addObject:[NSNumber numberWithInt:(count>8?8:count)]]; //add the last count
	
	// done with the db.  finalize the statement and close
	sqlite3_finalize (dbps);
	sqlite3_close(db);
	
	// check count array
	NSLog(@"--- INFO - COUNT ARRAY-> length of countArr:%d, current Cycle is %d ---",[countArr count],currentCycle);
//	NSLog(@"--- INFO - START END TIME -> Go to bed at %@, get up at %@ ---",startSleepTime,endSleepTime);
	NSLog(@"--- INFO - END-> loadDataFromDB ---");
	
	
	return countArr;
}


#pragma mark protocol S7GraphViewDataSource

- (NSUInteger)graphViewNumberOfPlots:(S7GraphView *)graphView {
	/* Return the number of plots you are going to have in the view. 1+ */
	return 1;
}

- (NSArray *)graphViewXValues:(S7GraphView *)graphView {
	/* An array of objects that will be further formatted to be displayed on the X-axis.
	 The number of elements should be equal to the number of points you have for every plot. */

	NSMutableArray *arrayX = [[NSMutableArray alloc] initWithCapacity:100];
	int count = [moveCountArray count];
	for ( int i = 0 ; i < count ; i ++ ) {
		[arrayX addObject:[NSNumber numberWithInt:i]];	
	}
	return arrayX;
}

- (NSArray *)graphView:(S7GraphView *)graphView yValuesForPlot:(NSUInteger)plotIndex {
	/* Return the values for a specific graph. Each plot is meant to have equal number of points.
	 And this amount should be equal to the amount of elements you return from graphViewXValues: method. */
	NSMutableArray *arrayY = [[NSMutableArray alloc] init];
	switch (plotIndex) {
		default:
		case 0:
			arrayY = [NSMutableArray arrayWithArray:moveCountArray];
		
			break;
	}
	
	return arrayY;
}

// post sleep data to Twitter
- (void) postToTwitter
{
	NSLog(@"--- INFO - TWITTER -> Click Post ---");
	NSString *urlStr = [NSString stringWithFormat:@"http://twitter.com/home?status= Went to bed at %@ and woke up at %@",startSleepTime,endSleepTime];
	NSLog(@"--- INFO - TWITTER -> http://twitter.com/home?status= Went to bed at %@ and got up at %@ ---",startSleepTime,endSleepTime);
	NSString *encodedURLStr = [ urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSURL *url = [NSURL URLWithString:encodedURLStr];
	[[UIApplication sharedApplication] openURL:url];
}   

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */




// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	
	// create views programmatically
	// S7GraphView -> self.view(IBOUTLET) 
	self.graphView = [[S7GraphView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];		
	self.view = self.graphView; 	
	self.graphView.dataSource = self;


}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	//
	// Create Labels
	//
	UILabel *label01 = [[UILabel alloc] initWithFrame:CGRectMake(270, 60, 60, 20)];
	label01.text = @"Awake";
	label01.textAlignment = UITextAlignmentLeft;
	label01.textColor = [UIColor blueColor];
//	label01.shadowColor = [UIColor whiteColor];
//	label01.shadowOffset = CGSizeMake(1,1);
	label01.font = [UIFont fontWithName:@"AppleGothic" size:12];
//	label01.backgroundColor = [UIColor greenColor];
	[label01 setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:label01];
	[label01 release];
	
	UILabel *label02 = [[UILabel alloc] initWithFrame:CGRectMake(270, 150, 60, 20)];
	label02.text = @"Light";
	label02.textAlignment = UITextAlignmentLeft;
	label02.textColor = [UIColor blueColor];
	label02.font = [UIFont fontWithName:@"AppleGothic" size:12];
	[label02 setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:label02];
	[label02 release];

	UILabel *label03 = [[UILabel alloc] initWithFrame:CGRectMake(270, 330, 60, 20)];
	label03.text = @"Deep";
	label03.textAlignment = UITextAlignmentLeft;
	label03.textColor = [UIColor blueColor];
	label03.font = [UIFont fontWithName:@"AppleGothic" size:12];
	[label03 setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:label03];
	[label03 release];

	UILabel *label04 = [[UILabel alloc] initWithFrame:CGRectMake(270, 348, 60, 20)];
	label04.text = @"(Hour)";
	label04.textAlignment = UITextAlignmentLeft;
	label04.textColor = [UIColor whiteColor];
	label04.font = [UIFont fontWithName:@"AppleGothic" size:10];
	[label04 setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:label04];
	[label04 release];

	UILabel *goToBedLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 10, 100, 20)];
	goToBedLabel.text = @"GO TO BED:";
	goToBedLabel.textAlignment = UITextAlignmentLeft;
	goToBedLabel.textColor = [UIColor whiteColor];
	goToBedLabel.font = [UIFont fontWithName:@"Arial" size:12];
	[goToBedLabel setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:goToBedLabel];
	[goToBedLabel release];
	
	UILabel *getUpLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 24, 100, 20)];
	getUpLabel.text = @"WAKE UP:";
	getUpLabel.textAlignment = UITextAlignmentLeft;
	getUpLabel.textColor = [UIColor whiteColor];
	getUpLabel.font = [UIFont fontWithName:@"Arial" size:12];
	[getUpLabel setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:getUpLabel];
	[getUpLabel release];
	
	//End of create labels
	
	
	// set up date formatter to parse dates from db strings
	if (! dateFormatter) {

		dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
		[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];

	}
	
	// set up NSNumber formatter for S7GraphView
	NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
	[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
	[numberFormatter setMinimumFractionDigits:0];
	[numberFormatter setMaximumFractionDigits:0];
	
	self.graphView.yValuesFormatter = numberFormatter; //y value - number formatter
	self.graphView.xValuesFormatter = numberFormatter;
       
	[numberFormatter release];
	
	self.graphView.backgroundColor = [UIColor darkGrayColor];
	
	self.graphView.drawAxisX = YES;
	self.graphView.drawAxisY = YES;
	self.graphView.drawGridX = NO;
	self.graphView.drawGridY = YES;
	
	self.graphView.xValuesColor = [UIColor whiteColor];
	self.graphView.yValuesColor = [UIColor whiteColor];
	
	self.graphView.gridXColor = [UIColor whiteColor];
	self.graphView.gridYColor = [UIColor whiteColor];
	
	self.graphView.drawInfo = NO;
	self.graphView.info = @"CHART";
	self.graphView.infoColor = [UIColor whiteColor];
	
	//When you need to update the data, make this call:	
	[self.graphView reloadData];
	
	// Load data from DB
	moveCountArray = [self loadDataFromDb];
	[moveCountArray retain];
	
	NSLog(@"--- INFO - VIEW DID LOAD -> Array Count is %d", [moveCountArray count]);
	for (NSString *obj in moveCountArray) {
		NSLog(@"---- INFO -moveCountArray memeber-> %@",obj);
	}
	
	NSLog(@"--- INFO - START END TIME -> Go to bed at %@, get up at %@ ---",startSleepTime,endSleepTime);
	
	// add start and end sleep time labels
	UILabel *startTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 10,120,20)];
	startTimeLabel.text = [NSString stringWithString:startSleepTime];
	startTimeLabel.textAlignment = UITextAlignmentLeft;
	startTimeLabel.textColor = [UIColor whiteColor];
	startTimeLabel.font = [UIFont fontWithName:@"Arial" size:12];
	[startTimeLabel setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:startTimeLabel];
	[startTimeLabel release];
	
	UILabel *endTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 24, 120, 20)];
	endTimeLabel.text = [NSString stringWithString:endSleepTime];
	endTimeLabel.textAlignment = UITextAlignmentLeft;
	endTimeLabel.textColor = [UIColor whiteColor];
	endTimeLabel.font = [UIFont fontWithName:@"Arial" size:12];
	[endTimeLabel setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:endTimeLabel];
	[endTimeLabel release];
	// end
	
	// add post to twitter button
	twitterBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	twitterBtn.frame = CGRectMake(88, 372, 144 , 25);
//	[button setTitle:@"Tweet" forState:UIControlStateNormal];
	UIImage *img = [UIImage imageNamed:@"twitter_button.png"];
	[twitterBtn setImage:img forState:UIControlStateNormal];
	[img release];
	[twitterBtn addTarget:self action:@selector(postToTwitter) forControlEvents:UIControlEventTouchUpInside];	
//	//add the button to the view
	[self.view addSubview:twitterBtn];
//	[twitterBtn release];
	
	NSLog(@"--- INFO - STAT VIEW -> viewDidLoad end ---");		
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

/*
-(void)viewDidAppear:(BOOL)animated{

}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[moveCountArray release];
	[twitterBtn release];
    [super dealloc];
}


@end
